extends CanvasLayer

@onready var fade: ColorRect = $fade
func _ready() -> void:
	#强制隐藏遮罩，防止它在编辑器里不小心被打开了
	fade.visible = false
	
	#将鼠标过滤设为忽略 (双重保险)
	#这样即使它不小心显示出来了，鼠标也能穿透它
	fade.mouse_filter = Control.MOUSE_FILTER_IGNORE


#外部接口
#普通淡入淡出效果
func change_scene_with_fade(path:String)->void:
	layer=10
	fade.show()
	var tween:=create_tween()
	tween.tween_property(fade,"color:a",1.0,0.2)
	await tween.finished
	await _change_scene_async(path)
	var tween_out:=create_tween()
	tween_out.tween_property(fade,"color:a",0.0,0.3)
	await tween_out.finished
	fade.hide()

#网格扩散效果
func change_scene_with_grid_spread(path:String)->void:
	layer = 10
	
	# 动态加载grid_spread场景
	var grid_spread_scene = load("res://others_assets/Grid_spread_transition/sence/grid_spread.tscn")
	var grid_spread = grid_spread_scene.instantiate()
	add_child(grid_spread)
	if grid_spread is Control:
		grid_spread.mouse_filter = Control.MOUSE_FILTER_IGNORE
	# 等待网格动画完成
	await grid_spread.animation_completed
	# 加载新场景
	await _change_scene_async(path)
	
	# 移除网格扩散效果
	grid_spread.queue_free()
	





#异步加载
func _change_scene_async(path:String)->void:
	
	ResourceLoader.load_threaded_request(path)
	
	while ResourceLoader.load_threaded_get_status(path)==ResourceLoader.THREAD_LOAD_IN_PROGRESS:
		await get_tree().create_timer(0.05).timeout
		
	if ResourceLoader.load_threaded_get_status(path)==ResourceLoader.THREAD_LOAD_LOADED:
		#get_tree().change_scene_to_packed(ResourceLoader.load_threaded_get(path))
		var packed_scene=ResourceLoader.load_threaded_get(path)
		var scene=packed_scene.instantiate()
		get_tree().root.add_child(scene)
		get_tree().current_scene.queue_free()
		get_tree().current_scene=scene
		
		await get_tree().process_frame
		
		if scene.has_signal("ready_for_display"):
			await scene.ready_for_display
			
	
func change_scene_simple(path: String) -> void:
	#强制提升层级，盖住 Dialogic 和所有 UI
	layer = 100 
	
	# 准备黑幕

	fade.color = Color.BLACK 
	fade.color.a = 0.0       
	fade.visible = true
	fade.mouse_filter = Control.MOUSE_FILTER_STOP # 拦截点击
	
	#淡入 (变黑)
	var tween = create_tween()
	tween.tween_property(fade, "color:a", 1.0, 0.5)
	
	#等待完全变黑
	await tween.finished
	
	get_tree().change_scene_to_file(path)
	
	# 等待两帧，确保新场景加载完毕
	await get_tree().process_frame
	await get_tree().process_frame
	
	#淡出 (变亮)
	var tween_out = create_tween()
	tween_out.tween_property(fade, "color:a", 0.0, 0.5)
	
	await tween_out.finished
	
	#还原状态
	fade.visible = false
	fade.mouse_filter = Control.MOUSE_FILTER_IGNORE
